package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Class for connection to database.
 * @author Tomas CASTA
 */
public class Db {

    /**
     * Constructor.
     */
    public Db() {
    }


    /** machine name */
    private String machine;
    /** database name */
    private String db;
    /** user name for database */
    private String user;
    /** password for database */
    private String pass;
    /** connection to database */
    private Connection connection;
    /** message for errors */
    private String msg;

    public void setMachine(String machine) {
        this.machine = machine;
    }

    public String getMachine() {
        return this.machine;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getUser() {
        return this.user;
    }

    public void setDb(String db) {
        this.db = db;
    }

    public String getDb() {
        return this.db;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    public String getPass() {
        return this.pass;
    }

    public String getMsg() {
        return msg;
    }



    /**
     * Constuctor.
     * @param machine String machine name
     * @param db String database name
     * @param user String user name for database
     * @param pass String password for database
     */
    public void setDb(String machine, String db, String user, String pass) {
        this.machine = machine;
        this.db = db;
        this.user = user;
        this.pass = pass;

    }

   /**
    * Connect to db with current params.
    * @return Connection connection, or null if error
    */
    public Connection connectToDB()  {

        /* URI for connecting to db */
        String uri = "jdbc:mysql://" + this.machine + "/" + this.db + "?user=" + this.user + "&password=" + this.pass + "&useUnicode=true&characterEncoding=UTF-8";
        try {

            /* Get class for connection */
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(uri);
            PreparedStatement stmt = null;

            /* Set names for utf8 encoding */
            stmt = connection.prepareStatement("SET NAMES utf8");
            stmt.execute();
            return connection;

        } catch (SQLException e) {
            msg = e.getMessage();
            return null;
        }
        catch (ClassNotFoundException e) {
            msg = e.getMessage();
            return null;
        }

    }
}
